/**
 * 费用预提模块业务入口
 */
import './presetVar'
import React, { Component } from 'react';
import { createPage, base, high, pageTo, promptBox } from 'nc-lightapp-front';
import { tableButtonClick, pageButtonClick, afterEvent, onRowDoubleClick, refreshButtonClick } from './events';
import initTemplate, {routeChange} from './initTemplate';
import {getAfterEventParams} from 'src/erm/sscrppublic/common/utils/formulaUtils';
import pubMessage from 'src/erm/sscrppublic/common/utils/pubMessage'
import Inspection from 'epmp/exports/components/Inspection';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import NCUploader from 'uap/common/components/NCUploader';
import attachments from 'uap/common/components/getAttachmentInfo';
import ApprovalTrans from 'uap/common/components/approvalTrans';
import { setTable } from 'src/erm/sscrppublic/common/utils/setComponentUsed'
//引入侧边栏
import AuditSidebar from 'sscia/auditSidebar/components/auditSidebar'
const { getAttachments, getAttachmentsInfo } = attachments;
const { NCModal } = base;
import {
    BillStyle,
    BillHead,
    BillBody,
    Form,
    CardTable,
    ButtonGroup
} from 'src/erm/sscrppublic/common/components/bill';

import {
    ProfileStyle,
    ProfileBody
} from 'src/erm/sscrppublic/common/components/profile';

import './index.less';

const pageButton = window.presetVar.pageButton;
window.assingUsers = [];
window.sureAssign = false;//确定指派
window.assignBillId = '';//有指派的情况下，第一次点保存提交实际保存成功的单据pk
window.djzt = '0'
class FYYTBill extends Component {

    constructor(props) {
        if (NODE_ENV == 'development') {
            window.NODE_ENV = 'development';
        }
        super(props);
        //初始化侧边栏
        this.auditSidebar = new AuditSidebar();
        setTable(props, 'billmodel')
        this.state = {
            btn: [presetVar.body.body1 + presetVar.areaBtnAction.del, presetVar.body.body1 + presetVar.areaBtnAction.edit],
            showModal: false,
            showUploader: false,
            target: null,
            billId: '',
            sourceData: null,
            showLinkBudget: false,
            isEffect: false,
            ShowApproveDetail: false,
            billtype: '',
            compositedata: '',
            compositedisplay: '',
            Title: '',
            uploaderBtnDisable: false, //附件上传按钮可用状态
            showAuditSidebar:false,
           
        }
        this.close = this.close.bind(this);
        initTemplate.call(this, props);
        this.pubMessage = new pubMessage(props);

        // TOP NCCLOUD-61317 增加公式编辑后联动 chengwebc ADD
        props.setRelationAfterEventCallBack && props.setRelationAfterEventCallBack((props, changedField, changedArea, oldCard, newCard, index, rowId)=>{
            let params = getAfterEventParams(props, changedField, changedArea, oldCard, newCard, index, rowId);
            params.map((one)=>{
                afterEvent.call(this, props, one.moduleId, one.key, one.value, one.changedrows, one.index)
            })
        });
        // BTM NCCLOUD-61317 增加公式编辑后联动 chengwebc

        props.use.form('head');
    }

    componentDidMount() {
        this.props.setHashChangeCallback(() => {
            routeChange.call(this, this.props);
      })
    }
    componentWillMount() {
                   window.onbeforeunload = () => {
                    let status = this.props.getUrlParam("status");
                    if (status == 'edit'||status == 'add') {
                        return ''/* 国际化处理： 确定要离开吗？*/
                    }
                }
            }


    close() {
        this.setState({ showModal: false });
    }

    cancel() {
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info) {
        this.setState({
            showLinkBudget: false
        })
    }
    openApprove = () => {
        this.setState({
            ShowApproveDetail: true
        })
    }

    closeApprove = () => {
        this.setState({
            ShowApproveDetail: false
        })
    }

    getAssginUser = (value) => {
        window.assingUsers = value;
        window.sureAssign = true;
        let props = this.props;
        if(props.getUrlParam('status') === 'browse'){
            pageButtonClick.call(this)[pageButton.billSubmit]();
        }else{
            pageButtonClick.call(this)[pageButton.billSaveSubmit]();
        }
        window.assignBillId = '';
    }

    turnOff() {
        window.presetVar.fromBtn = 'turnOff'
        this.setState({
            compositedisplay: false
        });
        window.sureAssign = false;
        window.assingUsers = [];
        let props = this.props;
        let billid = window.assignBillId;
        if(!billid){
            billid = props.form.getFormItemsValue('head', 'pk_accrued_bill').value;
        }
        pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'), status: 'browse', id: billid});
        routeChange.call(this, this.props)
    }

    onBeforeEvent(props, moduleId, key, value, index, record, status) {
        window.presetVar.bodyChangeValuesAll = record;
        return true;
    }

    onHideUploader = () => {
        this.setState({
            showUploader: false,
        });
        let id = this.props.getUrlParam('id') ? this.props.getUrlParam('id') : this.state.billId;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        getAttachments(id).then(lists => {
            this.props.button.setButtonTitle('fileManager', multiLang.get('201102FYYT-0014')/***'附件'**/ + ' ' + lists + ' ');
        })
    }

    renderErrorCenterState () {
        const { props } = this
        const { socket } = props;
        const status = props.form.getFormItemsValue('head', 'saga_status')
        if (!status || status.value !== '1') return null;
        
        this.props.button.toggleErrorStatus('head',{
            isError: true
        })

        const param = {
            headBtnAreaCode: 'head',
            formAreaCode: 'head',
            billtype: props.form.getFormItemsValue('head', 'saga_status').value,
            billpkname: 'pk_accrued',
            dataSource: 'erm.erbudgetmg.accrued.card'
        }
        return props.socket.connectMesg(param)
    }
    getFormHeadValueByKey(key) { // 根据 form 获取 head 中的值
        return this.props.form.getFormItemsValue("head", key).value || '';
    }
    toggleAuditSideBar(fromBtn) {
        //判断是否是提交 按钮或者保存提交按钮
        fromBtn = fromBtn||window.presetVar.fromBtn
       
        const head1 = window.presetVar.head.head1;
        const body1 = window.presetVar.body.body1;
        const pageId = window.presetVar.pageId;
        let billdata = this.props.createMasterChildData(pageId, head1, body1);
       
      
        let param = {};
        param.pk_group = this.props.form.getAllFormValue(head1).rows[0].values['pk_group'].value; // "集团pk"
        param.billtypecode = billdata.head.head.rows[0].values.pk_billtype.value; // "单据类型code" 
        param.tradetypecode = billdata.head.head.rows[0].values.pk_tradetype.value; // " 交易类型code"
        param.billid = this.props.getUrlParam('id'); // "单据主键pk"
        param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        param.iscreate = "Y"   // 注意应该是制单首次保存传Y,浏览态去掉这个参数！！！是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入 做初始化 智能审批
        param.isEdit = true;
        
        // param.pk_group = "0001A510000000000NKA"; // "集团pk"
        // param.billtypecode = "267X"; // "单据类型code" 
        // param.tradetypecode = "267X"; // " 交易类型code"
        // param.billid = "1001A510000000003V27"; // "单据主键pk"
        // param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        // param.iscreate =  "Y"  // 是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入
        // param.isEdit = true; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        console.log('param111111111111111111111',param,this.props.getUrlParam("status"),this.props.getUrlParam("scene"))
        if(!param.billid){
            return
        }
        
        //展示后的回调
        this.auditSidebar.showSidebar(param,null,()=>{
            // this.auditSidebar.refreshSidebar()
            setTimeout(()=>{
                const auditSidebarObj = this.auditSidebar.getSidebarStatistical()
                console.log('1111111',auditSidebarObj)
                const {pointTree} = auditSidebarObj
                if(!pointTree.length){
                    this.setState({
                        showAuditSidebar:false
                    })
                    window.presetVar.auditCanSave = 0
                    return
                }
                this.setState({
                    showAuditSidebar:true
                })

                for(let i=0;i<pointTree.length;i++){
                    const leaf = pointTree[i]
                    if(leaf.children&&leaf.children.length){
                        if(leaf.children.some(item=>item.ispass==='N')){
                            window.presetVar.auditCanSave = 3 //目前需求只要有不通过的就提示风险
                            //1 严格控制 2风险提示
                            // if(leaf.children.some(item=>item.values.controltype=='1')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 1
                            //     break
                            // }else if(leaf.children.some(item=>item.values.controltype=='2')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 2
                            //     break
                            // }
                        }else{
                            window.presetVar.auditCanSave = 0
                        }
                    }
                }
                
                //展示风险弹窗
                if(fromBtn==='saveSubmit'&&this.props.getUrlParam("status")==='browse'&&window.presetVar.auditCanSave>0){
                    let multiLang = this.props.MutiInit.getIntl(2011);
                    promptBox({
                        color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                        title: multiLang && multiLang.get('201102BCLF-0016'),
                        content: multiLang && multiLang.get('201102BCLF-0062'),
                        cancelBtnName:'收回',
                        beSureBtnClick: ()=>{
                            window.presetVar.auditCanSave = 0
                            
                        },
                        cancelBtnClick: () => {
                            pageButtonClick.call(this)[pageButton.billRecall]();
                            
                        }
                    })   
                }
            })
            
        })
        
    }
    render() {
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let btnModalConfig = {
            [pageButton.pageDel]: {
                // "2011-0004": "删除"
                // "2011-0005": "确认删除该单据吗？"
                title: multiLang && multiLang.get('2011-0004'),
                content: multiLang && multiLang.get('2011-0005'),
            },
            [pageButton.billInvalid]: {
                // "2011-0009": "作废",
                // "2011-0010": "确认作废该单据吗？"
                title: multiLang && multiLang.get('2011-0009'),
                content: multiLang && multiLang.get('2011-0010')
            },
            [pageButton.pageClose]: {
                // "2011-0007": "关闭"
                // "2011-0013": "确认关闭该单据吗？",
                title: multiLang && multiLang.get('2011-0007'),
                content: multiLang && multiLang.get('2011-0013')
            }
        }
        const { table,DragWidthCom} = this.props;
        let { createSimpleTable } = table;
        let { showUploader, target,showAuditSidebar } = this.state;
        let status = this.props.getUrlParam("status");
        let scene = this.props.getUrlParam("scene");
        const djzt =window.djzt
        return (
            <div className='billWrapper'>
                {this.renderErrorCenterState()}
                <DragWidthCom
                    leftDom={<BillStyle
                        {...this.props}
                    >
                        <BillHead
                            // "201102FYYT-0001": "费用预提单"
                            // title={multiLang && multiLang.get('201102FYYT-0001')}
                            title={this.state.Title}
                            refreshButtonEvent={refreshButtonClick.bind(this)}
                        >
                            <ButtonGroup
                                areaId="head"
                                buttonEvent={pageButtonClick.bind(this)}
                                modalConfig={btnModalConfig}
                                sagasButtonVisible={true}
                            />
    
                            <Form
                                areaId="head"
                                onAfterEvent={afterEvent.bind(this)}
                            />
                        </BillHead>
    
                        <BillBody>
                            <CardTable
                                areaId="accrued_detail"
                                totalItemCode="amount"
                                modelSave={pageButtonClick.call(this)['pageSave']}
                                onAfterEvent={afterEvent.bind(this)}
                                onBeforeEvent={this.onBeforeEvent.bind(this)}
                                showIndex={true}
                            >
                                <ButtonGroup
                                    buttonEvent={tableButtonClick.bind(this)}
                                />
                            </CardTable>
    
                            {this.state.isEffect == true ?
                                <CardTable
                                    areaId="accrued_verify"
                                    showIndex={true}
                                >
                                </CardTable>
                                : null}
    
                            <div>
                                {showUploader && < NCUploader
                                    disableButton={ this.state.uploaderBtnDisable }
                                    onHide={this.onHideUploader}
                                    billId={this.state.billId}
                                    targrt={target}
                                    placement={'bottom'} />
                                }
                            </div>
    
                            <div>
                                <ApproveDetail
                                    show={this.state.ShowApproveDetail}
                                    close={this.closeApprove}
                                    billtype={this.state.billtype}
                                    billid={this.state.billId}
                                />
                            </div>
    
                            <NCModal size="lg" show={
                                this.state.showModal
                            }
                                onHide={
                                    this.close
                                }>
                                <NCModal.Header closeButton='true'>
                                    {/*"201102FYYT-0002": "单据联查"*/}
                                    <NCModal.Title>{multiLang && multiLang.get('201102FYYT-0002')}</NCModal.Title>
                                </NCModal.Header>
    
                                <NCModal.Body>
                                    <div className="area-content">
                                        {createSimpleTable('billmodel', {
                                            onRowDoubleClick: onRowDoubleClick,
                                            showCheck: false,
                                            showIndex: true
                                        })}
                                    </div>
                                    <div>
    
                                    </div>
                                </NCModal.Body>
    
                            </NCModal>
    
    
                        </BillBody>
                    </BillStyle>}
                     rightDom={
                        this.auditSidebar.createComponent()
                    }
                    aside="right"
                    defLeftWid={showAuditSidebar && djzt != '0' && status === 'browse' && (scene !== 'sscermlink' && scene !== "linksce" && scene !== "lc" && scene !== "approve" && scene !== "approvesce" && scene !== 'zycl')
                        ? "20%" : '0%'}
                    
                    >

                    </DragWidthCom>
                
                <div>
                    <Inspection
                        show={this.state.showLinkBudget}
                        sourceData={this.state.sourceData}
                        cancel={this.cancel.bind(this)}
                        affirm={this.affirm.bind(this)}
                    />
                </div>
                <div>
                    {/*"201102FYYT-0003": "指派",*/}
                    {this.state.compositedisplay ? <ApprovalTrans
                        title={multiLang && multiLang.get('201102FYYT-0003')}
                        data={this.state.compositedata}
                        display={this.state.compositedisplay}
                        getResult={this.getAssginUser}
                        cancel={this.turnOff.bind(this)}
                    /> : ""}

                </div>
            </div>
        );

    }
}

FYYTBill = createPage({
    mutiLangCode: '2011',
    billinfo: {
        billtype: 'card',
        pagecode: presetVar.pageCode,
        headcode: presetVar.head.head1,
        bodycode: presetVar.body.body1
    },
    orderOfHotKey: [presetVar.body.body1]
    
})(FYYTBill);

export default FYYTBill;
